<template>
    <div class="chat-container">
      <div class="chat-header">
        <h2>AI心理咨询助手</h2>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" 
             :class="['message', message.type === 'ai' ? 'ai-message' : 'user-message']">
          <div class="message-content">
            <div class="message-avatar">
              <el-avatar :size="40" :src="message.type === 'ai' ? aiAvatar : userAvatar"></el-avatar>
            </div>
            <div class="message-text">
              <div class="message-bubble">
                {{ message.content }}
              </div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>
        </div>
      </div>
  
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          @keyup.enter.native="sendMessage"
        ></el-input>
        <el-button type="primary" @click="sendMessage" :disabled="!isConnected">发送</el-button>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  
  const user = JSON.parse(sessionStorage.getItem("users"))
  const id = user.userId

  // 头像
  const aiAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  const userAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  
  // WebSocket连接状态
  const isConnected = ref(false)
  const socket = ref(null)
  
  // 消息列表
  const messages = ref([
    {
      type: 'ai',
      content: '你好！我是AI心理咨询助手，有什么我可以帮你的吗？',
      time: formatTime(new Date())
    }
  ])
  
  // 输入消息
  const inputMessage = ref('')
  const messagesContainer = ref(null)
  
  // 格式化时间
  function formatTime(date) {
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  }
  
  // 初始化WebSocket连接
  const initWebSocket = () => {
    console.log("用户id为:"+id)
    const wsUrl = 'ws://localhost:8080/chat/'+id // 替换为你的WebSocket服务器地址
    console.log(wsUrl)
    socket.value = new WebSocket(wsUrl)
  
    socket.value.onopen = () => {
      isConnected.value = true
      ElMessage.success('连接成功')
    }
  
    socket.value.onmessage = (event) => {
      messages.value.push({
        type: 'ai',
        content: event.data,
        time: formatTime(new Date())
      })
      scrollToBottom()
    }
  
    socket.value.onerror = (error) => {
      console.error('WebSocket错误:', error)
      ElMessage.error('连接发生错误')
    }
  
    socket.value.onclose = () => {
      isConnected.value = false
      ElMessage.warning('连接已关闭')
    }
  }
  
  // 发送消息
  const sendMessage = () => {
    if (!inputMessage.value.trim()) {
      ElMessage.warning('请输入消息')
      return
    }
  
    if (!isConnected.value) {
      ElMessage.error('未连接到服务器')
      return
    }
  
    // 添加用户消息
    messages.value.push({
      type: 'user',
      content: inputMessage.value,
      time: formatTime(new Date())
    })
  
    // 发送消息到服务器
    socket.value.send(JSON.stringify({
      message: inputMessage.value
    }))
  
    // 清空输入框
    inputMessage.value = ''
    
    // 滚动到底部
    scrollToBottom()
  }
  
  // 滚动到底部
  const scrollToBottom = async () => {
    await nextTick()
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  }
  
  // 组件挂载时初始化WebSocket
  onMounted(() => {
    initWebSocket()
  })
  
  // 组件卸载时关闭WebSocket连接
  onUnmounted(() => {
    if (socket.value) {
      socket.value.close()
    }
  })
  </script>
  
  <style scoped>
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f5f7fa;
  }
  
  .chat-header {
    text-align: center;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .message {
    margin-bottom: 20px;
  }
  
  .message-content {
    display: flex;
    align-items: flex-start;
  }
  
  .message-avatar {
    margin-right: 10px;
  }
  
  .message-text {
    flex: 1;
  }
  
  .message-bubble {
    padding: 10px 15px;
    border-radius: 15px;
    max-width: 70%;
    word-wrap: break-word;
  }
  
  .message-time {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
  
  .ai-message .message-content {
    flex-direction: row;
  }
  
  .ai-message .message-bubble {
    background-color: #f0f2f5;
    color: #303133;
  }
  
  .user-message .message-content {
    flex-direction: row-reverse;
  }
  
  .user-message .message-avatar {
    margin-right: 0;
    margin-left: 10px;
  }
  
  .user-message .message-bubble {
    background-color: #409EFF;
    color: #fff;
  }
  
  .chat-input {
    display: flex;
    gap: 10px;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .chat-input .el-input {
    flex: 1;
  }
  
  .chat-input .el-button {
    align-self: flex-end;
  }
  </style>